#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Hosting;

namespace Utilities.IO
{
  public class FileUtils
  {
    public static FileSystemInfo GetFileSystemInfo(string path)
    {
      if (File.Exists(path))
      {
        return new FileInfo(path);
      }
      else if (Directory.Exists(path))
      {
        return new DirectoryInfo(path);
      }

      return null;
    }

    /// <summary>
    /// Removes invalid file name characters from the specified string.
    /// </summary>
    /// <param name="s">The filename string.</param>
    /// <returns></returns>
    public static string ToValidFileName(string s)
    {
      return ToValidFileName(s, string.Empty, null);
    }

    public static string ToValidFileName(string s, string invalidReplacement)
    {
      return ToValidFileName(s, invalidReplacement, null);
    }

    public static string ToValidFileName(string s, string invalidReplacement, string spaceReplacement)
    {
      StringBuilder sb = new StringBuilder(s);

      foreach (char invalidFileNameChar in Path.GetInvalidFileNameChars())
      {
        if (invalidReplacement != null)
          sb.Replace(invalidFileNameChar.ToString(), invalidReplacement);
      }

      if (spaceReplacement != null)
        sb.Replace(" ", spaceReplacement);

      return sb.ToString();
    }

    public static string ResolvePath(string basePath, string relativePath)
    {
      string resolvedPath = Path.Combine(basePath, relativePath);
      resolvedPath = Path.GetFullPath(resolvedPath);

      return resolvedPath;
    }

    public static string MapPath(string path)
    {
      if (Path.IsPathRooted(path))
      {
        return path;
      }
      else if (HostingEnvironment.IsHosted)
      {
        return HostingEnvironment.MapPath(path);
      }
      else if (VirtualPathUtility.IsAppRelative(path))
      {
        string physicalPath = VirtualPathUtility.ToAbsolute(path, "/");
        physicalPath = physicalPath.Replace('/', '\\');
        physicalPath = physicalPath.Substring(1);
        physicalPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, physicalPath);

        return physicalPath;
      }
      else
      {
        throw new Exception("Could not resolve non-rooted path.");
      }
    }
  }
}